package org.gh.blackcloud.filter;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gh.blackcloud.RemoteStore;
import org.gh.blackcloud.ReplaceHandler;
import org.gh.blackcloud.ResouceUtils;
import org.gh.blackcloud.task.TaskCenter;

public class ResourceFilter implements Filter {

	private String[] resourceSuffix = {".gif", ".png", ".jpg", "jpeg"};
	
	private RemoteStore remoteStore = new RemoteStore();
	private TaskCenter taskCenter = new TaskCenter();
	private ReplaceHandler replaceHandler = new ReplaceHandler(remoteStore);
	
	public void init(FilterConfig config) throws ServletException {
//		remoteStore.init();
	}
	
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		HttpServletResponse response = (HttpServletResponse) servletResponse;
		
		//**资源上传
		String requestUrl = request.getRequestURL().toString();
		System.out.println(requestUrl);
		if( ResouceUtils.isResource(requestUrl, resourceSuffix) ) {
			//查看资源，如果未包含该资源，则上传该资源
			if(!remoteStore.contains(requestUrl)) {
				remoteStore.put(requestUrl, null);
				taskCenter.newOne(requestUrl);
			}
		}
		
		//**资源替换
		// 使用我们自定义的响应包装器来包装原始的ServletResponse
		ResourceReplaceWrapper wrapper = new ResourceReplaceWrapper(response);
		chain.doFilter(servletRequest, wrapper);
		String result = wrapper.result();
//		result = replaceHandler.replaceHtmlLocal2Remote(result, request.getRequestURL().toString());
		//输出到页面
		OutputStream out = response.getOutputStream();
		PrintWriter writer = new PrintWriter(out);
		writer.write(result);
		writer.flush();
		writer.close();
	}
	
	public void destroy() {
	}

}
